package com.hong.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hong.common.BusinessException;
import com.hong.entity.SysRole;
import com.hong.entity.SysRoleMenu;
import com.hong.entity.SysUserRole;
import com.hong.mapper.SysRoleMapper;
import com.hong.mapper.SysRoleMenuMapper;
import com.hong.mapper.SysUserRoleMapper;
import com.hong.service.ISysRoleService;

/**
 * SysRole 表数据服务层接口实现类
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Autowired
	private SysRoleMenuMapper sysRoleMenuMapper;

	@Override
	@Transactional
	public boolean deleteByIds(List<String> roleIds) {
		for (String roleId : roleIds) {
			SysRole role = this.getById(roleId);
			if (countUserRoleByRoleId(roleId) > 0) {
				throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
			}
		}
		// 删除角色与菜单关联
		QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<SysRoleMenu>();
		queryWrapper.in("role_id", roleIds);
		sysRoleMenuMapper.delete(queryWrapper);
		return this.removeByIds(roleIds);
	}

	private int countUserRoleByRoleId(String roleId) {
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
		queryWrapper.eq("role_id", roleId);
		return sysUserRoleMapper.selectList(queryWrapper).size();
	}

}